package org.activemonitoring.monitors;

import javax.ws.rs.core.MediaType;

import org.activemonitoring.datastore.dao.DataStoreDao;
import org.activemonitoring.datastore.entity.MeasureEntity;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sun.jersey.api.client.Client;

import static org.junit.Assert.assertEquals;

public class MonitoringServletFilterCase {

    private static final String MODULE_NAME = "/test";
    private Server server;
    private DataStoreDao dataStoreDao;

    @Before
    public void setUp() throws Exception {
        this.server = new Server();
        SocketConnector connector = new SocketConnector();
        connector.setPort(8080);
        this.server.setConnectors(new Connector[] { connector });
        WebAppContext context = new WebAppContext();
        context.setServer(this.server);
        context.setContextPath(MODULE_NAME);
        context.setWar("src/test/webapp");
        this.server.addHandler(context);
        this.server.start();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context
                .getServletContext());
        this.dataStoreDao = applicationContext.getBean("dataStoreDao", DataStoreDao.class);
    }

    @After
    public void tearDown() throws Exception {
        this.dataStoreDao.clear();
        this.server.stop();
    }

    @Test
    public void testMonitoringServletFilter() throws Exception {
        Client client = Client.create();
        String rootUrl = "http://localhost:8080";
        String serviceUrl = "/test/services";
        String pingUrl = serviceUrl + "/ping";
        String errorUrl = serviceUrl + "/ping/error";
        client.resource(rootUrl + pingUrl).accept(MediaType.TEXT_PLAIN_TYPE).get(String.class);
        try {
            client.resource(rootUrl + errorUrl).accept(MediaType.TEXT_PLAIN_TYPE).get(String.class);
        } catch (Exception e) {
            // An excepted error has occured
        }
        Thread.sleep(100L);
        assertEquals(2, this.dataStoreDao.getMeasures().size());
        MeasureEntity measure = this.dataStoreDao.getMeasures().get(0);
        assertEquals(MODULE_NAME, measure.getModuleName());
        assertEquals(pingUrl, measure.getName());
        assertEquals(false, measure.isHasError());
        measure = this.dataStoreDao.getMeasures().get(1);
        assertEquals(MODULE_NAME, measure.getModuleName());
        assertEquals(errorUrl, measure.getName());
        assertEquals(true, measure.isHasError());
    }
}
